package server;

import java.awt.RenderingHints.Key;
import java.io.*;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;


public class EstraiChiaviCert {

	public EstraiChiaviCert(){
	
	}
	
	/*public static void main(String[] args) {
		EstraiChiaviCert ec = new EstraiChiaviCert();
		//ec.leggi_chiavi();
		PublicKey pub = ec.getMyPubKey();
		//System.out.println(pub);
		PrivateKey priv = ec.getMyPrivKey();
		//System.out.println(priv);
		
	}*/

	
	
	
	
	
	@SuppressWarnings("finally")
	public PublicKey getMyPubKey(){
		char[] password = "server".toCharArray();
		String alias = "serverKey";
		PublicKey serverPubKey=null;
		try {
			
			FileInputStream fis = new FileInputStream("./certificati/serverKeystore.jks");
			KeyStore keystore = KeyStore.getInstance("JKS");
			keystore.load(fis, password);
			
			java.security.cert.Certificate cer = keystore.getCertificate(alias);
			//ricavo chiave pubblica
			serverPubKey =cer.getPublicKey();
			//System.out.println("Chiave Pubblica= "+ clientPubKey);
			
			
			
		} catch (FileNotFoundException e) {
			System.out.println("FileNotFound");
		} catch (KeyStoreException e) {
			System.out.println("KeyStoreException");
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlg");
		} catch (CertificateException e) {
			System.out.println("Certificate");
		} catch (IOException e) {
			System.out.println("IO");
		} 
	finally{
		return serverPubKey;
	}
	}
	
	
	
	
	@SuppressWarnings("finally")
	public PrivateKey getMyPrivKey(){
		char[] password = "server".toCharArray();
		String alias = "serverKey";
		PrivateKey serverPrivKey=null;
		try {
			
			FileInputStream fis = new FileInputStream("./certificati/serverKeystore.jks");
			KeyStore keystore = KeyStore.getInstance("JKS");
			keystore.load(fis, password);
			
			//java.security.cert.Certificate cer = keystore.getCertificate(alias);
			//ricavo chiave privata
			KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(alias, new KeyStore.PasswordProtection(password));
			serverPrivKey = pkEntry.getPrivateKey();
			//System.out.println("Chiave privata: "+ clientPrivKey);
			
		} catch (FileNotFoundException e) {
			System.out.println("FileNotFound");
		} catch (KeyStoreException e) {
			System.out.println("KeyStoreException");
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlg");
		} catch (CertificateException e) {
			System.out.println("Certificate");
		} catch (IOException e) {
			System.out.println("IO");
		} 
	finally{
		return serverPrivKey;
	}
	}
	
	
	
	
	
}
